package com.kylin.common.taglib;

import java.util.List;
import java.util.Locale;

import org.apache.struts.Globals;
import org.apache.struts.util.MessageResources;

import com.kylin.common.Constants;
import com.kylin.common.dict.ISelectOption;
import com.kylin.common.exception.SystemException;
import com.kylin.common.util.MemObjFactory;
import com.kylin.common.util.UTool;

/**
 * 生成 语言种类 或国家地区的下拉菜单
 * type 属性  设定下拉菜单的数据种类
 *     type=Constants.ALLLANGUAGE  所有语言 
 *     type=Constants.SYSLANGUAGE  系统支持的语言 
 *     type=Constants.ALLCOUNTRY   所有国家地区 
 * 其他属性参见 SelectTag    
 * @author lzh
 *
 */
public class NationalTag extends SelectTag {

	protected String getOptions() throws InstantiationException, IllegalAccessException,
			ClassNotFoundException {
		MessageResources mess = MessageResources.getMessageResources("message");
		StringBuffer sb = new StringBuffer();
		List datas = null;
		if (dictName == null || dictName.equals(""))
			throw new SystemException("未指定下拉菜单的数据源种类，请选择 language 或 country");
		Locale loc;
		if (language == null || language.equals(""))
			loc = (Locale) pageContext.getAttribute(Globals.LOCALE_KEY, pageContext.SESSION_SCOPE);
		else
			loc = UTool.getLocaleByLang(language);
		if(loc == null)
			loc = Locale.getDefault();
		if (dictName.equals(Constants.SYSLANGUAGE)){
			datas = MemObjFactory.getSysLanguageList(loc);
			if (this.notEmpty == null || !notEmpty.equalsIgnoreCase("true"))
				sb.append("<option value=''>-- ").append( mess.getMessage(loc,"lang.01")).append(" --</option>");			
		}else if (dictName.equals(Constants.ALLLANGUAGE)){
			datas = MemObjFactory.getAllLanguageList(loc);
			if (this.notEmpty == null || !notEmpty.equalsIgnoreCase("true"))
				sb.append("<option value=''>-- ").append( mess.getMessage(loc,"lang.01")).append(" --</option>");			
		}else if (dictName.equals(Constants.ALLCOUNTRY)){
			datas = MemObjFactory.getAllCountryList(loc);
			if (this.notEmpty == null || !notEmpty.equalsIgnoreCase("true"))
				sb.append("<option value=''>-- ").append( mess.getMessage(loc,"base.13")).append(" --</option>");			
		}
		// 如果没有定义下拉字典名，则尝试查找内存中的listName定义的 list
		if(datas == null && listName !=  null)
			datas = (List)pageContext.getAttribute(listName);

		if (datas == null || datas.size() == 0)
			return "<option>-- 无选项 --</option>";
		for (int i = 0; i < datas.size(); i++) {
			ISelectOption bean = (ISelectOption) datas.get(i);
			sb.append("\n<option value=\"").append(bean.getValue()).append("\"");
			if (matchValue(bean.getValue()))
				sb.append(" selected='true' ");
			sb.append(">");
			sb.append(bean.getName()).append("</option>");
		}
		return sb.toString(); 
	}

}
